<script>
export default {
  name: "myinfo",
  data() {
    return {
      form: {
        id: '',
        nickname: '',
        avatar_url: '',
      },
      action:  this.$baseUrl + '/api/upload/file',
      fileList: []
    }
  },
  onShow() {
    if (!this.$store.state.userInfo.id) {
      uni.navigateTo({
        url: '/pages/user/login'
      })
      return
    }
    this.form = this.$store.state.userInfo
    this.$api.memberDetail(this.form.id).then(res => {
      this.form.id = res.id
      this.form.nickname = res.nickname
      if (res.avatar_url) {
        this.form.avatar_url = res.avatar_url
        this.fileList = [{
          url:  res.avatar_url
        }]
      }
    })
  },
  methods: {
    successFile(e) {
      this.form.avatar_url = e.data.url
    },
    removeFile() {
      this.form.avatar_url = ''
    },
    submit() {
      this.$api.memberUpdate({
        ...this.form,
      }).then(() => {
        uni.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        })
        // 更新缓存
        this.$store.commit('SET_USERINFO', this.form)
      })
    },
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定退出登录？',
        success: (res) => {
          if (res.confirm) {
            this.$store.commit('SET_USERINFO', {})
            uni.navigateTo({
              url: '/pages/user/login'
            })
          }
        }
      })
    }
  }
}
</script>

<template>
  <div class="myinfo">
    <div class="form-box">
      <u-form :model="form" ref="uForm">
        <u-form-item label="姓名"><u-input v-model="form.nickname" /></u-form-item>
        <u-form-item label="头像">
          <u-upload :action="action" max-count="1" :file-list="fileList" @on-success="successFile" @on-remove="removeFile"></u-upload>
        </u-form-item>
      </u-form>
    </div>
    <div class="button button-primary" style="margin: 30rpx 0;width: 100%" @click="submit" >保存</div>
    <div class="button button-primary" style="margin: 30rpx 0;width: 100%" @click="logout" >退出登录</div>
  </div>
</template>

<style lang="scss">
.myinfo {
  height: 100%;
  background-color: #F5F7FA;
  padding: 20rpx;
  .primary-button {
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 41px;
    line-height: 41px;
    font-size: 16px;
    color: #fff;
    background-color: #2aac34;
    border-radius: 5px;
    box-sizing: border-box;
  }
  .form-box {
    border-radius: 10px;
    background-color: #FFFFFF;
    padding: 20rpx;
  }
}
</style>
